package commands;

import java.util.*;

import javax.microedition.lcdui.*;

public class Dispatcher implements CommandListener{

	private Hashtable m_listeners;
	
	private static Dispatcher m_instance; 

	private Dispatcher() {
		m_listeners = new Hashtable();
	}
	
	public static Dispatcher getInstance(){
		if(m_instance == null){
			m_instance = new Dispatcher();
		}
		return m_instance;
	}

	public void registerListener(CommandListener listener, String commandLabel){
		if(!m_listeners.containsKey(commandLabel))
		{
			m_listeners.put(commandLabel, new Vector());
		}
		Vector listeners = (Vector)m_listeners.get(commandLabel);
		listeners.addElement(listener);
	}
	
	public void handleCommand(Command command){
	
		if(!m_listeners.containsKey(command.getLabel())){
			return;
		}
		Vector listeners = (Vector)m_listeners.get(command.getLabel());
		for (int i = 0; i < listeners.size(); ++i){
			CommandListener listener = (CommandListener)listeners.elementAt(i);
			listener.commandAction(command, null);
		}		
	}

	public void commandAction(Command cmd, Displayable arg1) {
		if(cmd.getCommandType() == Command.ITEM){
			handleCommand(cmd);
		}
	}	
}
